/**
 * Author:  LiShibin.
 * Date:    2016/12/12.
 * File：   .
 */
let HmacMD5 = require('crypto-js/hmac-md5.js')

/***
 * 获取签名
 * @param sec 是否加密
 * @param url 请求地址
 * @param ak accessTokenKey
 * @param at accessToken
 * @param ct 参数
 * @return {Promise.<*>}
 * 说明：async函数返回的是promise对象
 */
async function getSign (ak, at, ct) {
  let clientId = window.localStorage.getItem('clientId') || ''
  let pa = at + [clientId, ak, ct].sort().join('').replace(/\t|\r|\n/g, '') + at
  console.log('ct', ct)
  let sign
  try {
    sign = HmacMD5(pa, at).toString().toUpperCase()
  } catch (e) {
    console.log('签名错误')
    console.log(e)
  }
  return sign
}
/**
 *  针对obj的key进行排序方法
 */
function sortObjectKeys (obj) {
  var tmp = {}
  Object.keys(obj).sort().forEach(function (k) {
    tmp[k] = obj[k]
  })
  return tmp
}
/***
 * 获取头部
 * @param type
 * @param url
 * @param data
 * @return {Promise.<{Content-Type: string, ehome-head-params: string}>}
 * 说明：async函数返回的是promise对象
 */
async function getHead (type, data, url) {
  let clientId = window.localStorage.getItem('clientId') || ''
  let args = []
  let ak = window.localStorage.getItem('accessTokenKey') || ''
  let at = window.localStorage.getItem('accessToken') || ''
  let ct = JSON.stringify(sortObjectKeys(data))
  let sign = await getSign(ak, at, ct)
  let userId = window.localStorage.getItem('userId') || 'U4E2C821DF43E4ED7B1BE3384BC4A169D'
  // let sec = 'F'
  let header
  switch (type) {
    case 'upload':
      args.push(clientId)
      args.push(ak)
      args.push(sign)
      args.push('')
      header = {
        'Content-Type': 'application/octet-stream',
        'fjxhx-gis-head-params': args.join(';')
      }
      break
    case 'inner':
      args.push(userId)
      args.push(url)
      args.push('')
      header = {
        'Content-Type': 'application/octet-stream',
        'ehome-head-params': args.join(';')
      }
      break
    case 'oauth':
      args.push(clientId)
      args.push('')
      header = {
        'Accept': '*/*',
        'fjxhx-gis-head-params': args.join(';')
      }
      break
    case 'outer':
      args.push(clientId)
      args.push(ak)
      args.push(sign)
      args.push('')
      header = {
        'Accept': '*/*',
        'fjxhx-gis-head-params': args.join(';')
      }
      break
  }
  return header
}

export default getHead
